package com.atdel.demo20;


import org.junit.Test;

import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.sql.SQLOutput;
import java.util.Scanner;

/**
 * @BelongsProject: java_study
 * @BelongsPackage: com.atdel.demo20
 * @Author: Del
 * @CreateTime: 2025-03-17  15:52
 * @Description:
 * 使用反射机制来实现用户输入一个年份，判断是闰年还是平年
 *     Scanner sc = new Scanner(System.in) ;
 *     sc.nextInt()
 * @Version: 1.0
 */
public class ReflectDemo {
    public static void main(String[] args) {
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        try {
            // 加载 Scanner 类
            Class<?> aClass = systemClassLoader.loadClass("java.util.Scanner");
            Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(InputStream.class);
            declaredConstructor.setAccessible(true);

            // 创建 Scanner 实例
            Object scannerInstance = declaredConstructor.newInstance(System.in);

            // 获取 nextInt 方法
            Method nextIntMethod = aClass.getMethod("nextInt");
            nextIntMethod.setAccessible(true);

            // 提示用户输入
            System.out.print("请输入年份：");
            System.out.flush();

            // 调用 nextInt 方法
            int year = (int) nextIntMethod.invoke(scannerInstance);

            // 判断是否为闰年
            if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
                System.out.println(year + " 是闰年");
            } else {
                System.out.println(year + " 是平年");
            }

            // 关闭 Scanner
            Method closeMethod = aClass.getMethod("close");
            closeMethod.invoke(scannerInstance);
        } catch (Exception e) {
            System.out.println("发生错误：" + e.getMessage());
        }
    }

    /**
     * 判断是否为闰年
     *
     * @param year 年份
     * @return true 如果是闰年，否则 false
     */
    private boolean isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }
}

